﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Globalization;
using System.IO;
using System.Data;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;

namespace TextAnalyzer
{
    internal enum ExportType
    {
        Excel = 1,
        CSV
    }
    internal class EnumMatchToBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null || parameter == null) return false;

            string checkValue = value.ToString();
            string targetValue = parameter.ToString();
            return checkValue.Equals(targetValue, StringComparison.InvariantCultureIgnoreCase);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null || parameter == null) return null;

            bool useValue = (bool)value;
            string targetValue = parameter.ToString();
            if (useValue) return Enum.Parse(targetType, targetValue);

            return null;
        }
    }   
    internal class Exporter
    {
        private TextViewModel mViewModel=null;
        private string mSeperator=",";
        public Exporter()
        {
            if (null == mViewModel) mViewModel = TextViewModel.GetInstance();
        }
        public void Export(List<KeyViewModel> listKeys, string strPath)
        {
            if (0 == mViewModel.Contents.Rows.Count) throw new ArgumentNullException("Contents", "내보낼 정보가 없습니다.");
            if (null == listKeys) throw new ArgumentNullException("List", "출력할 대상을 선택하십시오.");
            else
            {
                if (0 < listKeys.Count)
                {
                    if (0 < mViewModel.ExportTarget)
                    {
                        switch (mViewModel.ExportTarget)
                        {
                            case ExportType.CSV:
                                WriteCSV(listKeys, strPath);
                                break;
                            case ExportType.Excel:
                                WriteExcel(listKeys, strPath);
                                break;
                        }
                    }
                    else throw new ArgumentNullException("ExportTarget", "내보낼 대상을 선택해야 합니다.");
                }
                else throw new ArgumentException("출력할 대상을 선택하지 않았습니다.");
            }
        }
        private void WriteCSV(List<KeyViewModel> list, string strPath)
        {
            if (null != list)
            {
                StreamWriter _writer = new StreamWriter(strPath, false);
                string _header = null;
                foreach (KeyViewModel _model in list) _header += _model.Header + mSeperator;
                _header = _header.Remove(_header.Length - mSeperator.Length);
                _writer.WriteLine(_header);

                if (null != mViewModel.Contents)
                {
                    if (null != mViewModel.Contents.Rows)
                    {
                        foreach (DataRow _row in mViewModel.Contents.Rows)
                        {
                            string _line = null;
                            foreach (KeyViewModel _model in list)
                            {
                                string _key = _model.Key;
                                if (_key.Contains(".")) _key = _key.Remove(_key.Length - 1);
                                _line += _row[_key] + mSeperator;
                            }
                            _line = _line.Remove(_line.Length - mSeperator.Length);
                            _writer.WriteLine(_line);
                        }
                    }
                }
                _writer.Close();
            }
        }
        private void WriteExcel(List<KeyViewModel> list, string strPath)
        {
            if (null != list)
            {
                Excel.Application _excel = null;
                Excel.Workbooks _books = null;
                Excel.Workbook _book = null;
                Excel.Worksheet _sheet = null;
                try
                {
                    _excel = new Excel.Application();
                    _books = _excel.Workbooks;
                    _book = _books.Add(Missing.Value);
                    _sheet = _book.Worksheets.get_Item(1) as Excel.Worksheet;
                    _sheet.Name = mViewModel.Contents.TableName;

                    for (int i = 0; i < list.Count; i++) _sheet.Cells[1, i + 1] = list[i].Header;
                    for (int i = 0; i < mViewModel.Contents.Rows.Count; i++)
                    {
                        DataRow _row = mViewModel.Contents.Rows[i];
                        for (int j = 0; j < list.Count; j++)
                        {
                            string _key = list[j].Key;
                            if (_key.Contains(".")) _key = _key.Remove(_key.Length - 1);
                            _sheet.Cells[2 + i, 1 + j] = _row[_key].ToString();
                        }
                    }

                    
                    _book.SaveAs(strPath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Missing.Value, Missing.Value, Missing.Value, Missing.Value,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                    _book.Close(false, Missing.Value, Missing.Value);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (null != _sheet) System.Runtime.InteropServices.Marshal.ReleaseComObject(_sheet);
                    if (null != _book) System.Runtime.InteropServices.Marshal.ReleaseComObject(_book);
                    if (null != _books) System.Runtime.InteropServices.Marshal.ReleaseComObject(_books);
                    if (null != _excel) System.Runtime.InteropServices.Marshal.ReleaseComObject(_excel);
                }
            }
        }
    }
}
